package GUI;

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileFilter;

import Client.BusinessImplements;
import Controler.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import javax.swing.border.LineBorder;
/**
 * @author Lucie
 * Class name: Add_New_Item_Panel
 * extend  Abstract_Jpanel
 * purpose: this panel get a item name,adition,location,authors name,subjects name,pdf,description from the user and call the controller 
 * to add new item to the data base
 */
public class Add_New_Item_Panel extends Abstract_Jpanel {
	private JTextField textbook_name;
	private JTextField textField_book_adition;
	private JTextField textField_location;
	private  JTextArea textArea_description;
	private JComboBox comboBox_wanted;
	private Add_new_item_controler add_new_item_controler;
	private Add_new_item_controler add_new_item_controler1;
	private ArrayList<String> str_autor_name;
	private ArrayList<String> str_subjects;
	private JComboBox comboBox_author_name;
	private JComboBox comboBox_book_subject;
	private ArrayList<String> all_authors;
	private ArrayList<String> all_subject;
	private String[] all_authors_name;
	private String[] all_subject_name;
	private String[] all_authors_id;
	private String[] all_subject_id;
	private JButton btnNewButton;
	private JPanel panel;
	private String decoded=null;
	
	
	private JButton btnAdd_book_subjec;
	private JButton btnAdd_author_name;
	
	private JButton btnApply ;
	private JButton btnBack;
	private JButton btnDeleteAll;
	/**
	 * Create the panel.
	 * 
	 */
	public Add_New_Item_Panel() {
		setLayout(null);
		
	
		
		
		 btnApply = new JButton("apply");
		 btnApply.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		String[] sw= new String[]{"kjl","olkpo","kp","ok"};
		//=====================================
		
		/*
		 * btnApply=When you click this button you will call get_data()
		 * a method of the controller of this panel if this method return true we will
		 * call the methods of this class next_screen_success(),empty_text_fields();
		 * else we call next_screen_faild(add_new_item_controler1.get_msg());	
		 * 	add_new_item_controler1.get_msg(); return the msg from the controller with all
		 * the error msg.
		 */
		btnApply.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				add_new_item_controler1=new Add_new_item_controler();
				if(add_new_item_controler1.get_data(get_book_name(),  get_book_adition(),  get_location(),get_wanted(), get_subjects(), get_autor_name(), get_description(),decoded))
				{
					next_screen_success();
					empty_text_fields();
					
				}
				else {
					next_screen_faild(add_new_item_controler1.get_msg());
					
				}
				
				
			
			}
		});
		btnApply.setBounds(673, 626, 89, 34);
		add(btnApply);
		/*
		 * btnBack ;When you click this button you will return to 
		 * sing in panel screen
		 */
		btnBack = new JButton("back");
		btnBack.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			Sign_in_panel sip=new Sign_in_panel();
			on_screen_unload();
			BusinessImplements.GetInstance().getMainFrame().setContentPane(sip);
			sip.setSize(getMaximumSize());
			sip.on_screen_load();
				
				
			}
		});
		btnBack.setBounds(140, 626, 89, 34);
		add(btnBack);
		
		JLabel lblAddItem = new JLabel("Add Item");
		lblAddItem.setForeground(new Color(25, 25, 112));
		lblAddItem.setFont(new Font("MV Boli", Font.BOLD, 30));
		lblAddItem.setBounds(65, 11, 219, 34);
		add(lblAddItem);
		/*
		 * btnDeleteAll=When you click this button we will call the method,empty_text_fields();
		 * that will empty all text fields
		 */
		btnDeleteAll = new JButton("delete all ");
		btnDeleteAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				empty_text_fields();
			}
		});
		btnDeleteAll.setBounds(530, 626, 94, 34);
		add(btnDeleteAll);
		btnDeleteAll.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new LineBorder(SystemColor.activeCaption, 6));
		panel_1.setBackground(SystemColor.inactiveCaption);
		panel_1.setBounds(53, 46, 800, 569);
		add(panel_1);
		panel_1.setLayout(null);
		
		 comboBox_author_name = new JComboBox();
		 comboBox_book_subject = new JComboBox();
		 comboBox_wanted = new JComboBox();
		 btnAdd_book_subjec = new JButton("add");
		 btnAdd_book_subjec.setFont(new Font("Tahoma", Font.PLAIN, 14));
		 btnAdd_author_name = new JButton("add");
		 btnAdd_author_name.setFont(new Font("Tahoma", Font.PLAIN, 14));
		 textArea_description = new JTextArea();
		 
			
				
			
		panel = new JPanel();
		panel.setBorder(new LineBorder(SystemColor.control, 6));
		panel.setBounds(73, 30, 636, 494);
		panel_1.add(panel);
		panel.setBackground(new Color(220, 220, 220));
		panel.setForeground(Color.BLACK);
		panel.setLayout(null);
		
		JLabel lblBookName = new JLabel("book name:");
		lblBookName.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblBookName.setBounds(15, 10, 83, 28);
		panel.add(lblBookName);
		
		JLabel lblAuthorName = new JLabel("author full name:");
		lblAuthorName.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblAuthorName.setBounds(10, 144, 107, 28);
		panel.add(lblAuthorName);
		
		JLabel lblBookSubject = new JLabel("book subject:");
		lblBookSubject.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblBookSubject.setBounds(15, 197, 88, 21);
		panel.add(lblBookSubject);
		
		textbook_name = new JTextField();
		textbook_name.setBounds(127, 16, 115, 20);
		panel.add(textbook_name);
		textbook_name.setColumns(10);
		
		
		btnAdd_book_subjec.setBounds(262, 192, 66, 30);
		panel.add(btnAdd_book_subjec);
		
		JLabel lblWanted = new JLabel("wanted :");
		lblWanted.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblWanted.setBounds(10, 255, 66, 15);
		panel.add(lblWanted);
		
			comboBox_wanted.setModel(new DefaultComboBoxModel(new String[] {"NO", "YES"}));
			comboBox_wanted.setBounds(133, 254, 54, 28);
			panel.add(comboBox_wanted);
			
			comboBox_author_name.setBounds(127, 150, 115, 22);
			panel.add(comboBox_author_name);
			
					/*
					 * btnAdd_author_name; When you click this button you will enter to an array list
					 * "str_autor_name" a name of an author that was selected in the comboBox_author_name
					 */
					btnAdd_author_name.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							int flag=1;
							if (!comboBox_author_name.getSelectedItem().toString().isEmpty())
							{
								for(int i=0;i< str_autor_name.size();i++)
								{
									if(str_autor_name.get(i).equals(comboBox_author_name.getSelectedItem()))
									{	
										flag=0;
								   		break;
								   	}
								}
								if(flag==1)
							 str_autor_name.add(comboBox_author_name.getSelectedItem().toString());
							}
						}
					});
					/*
					 *  * btnAdd_book_subjec; When you click this button you will enter to an array list
					 * "str_subjects" a name of an subject that was selected in the comboBox_book_subject
					 */
					 btnAdd_book_subjec.addActionListener(new ActionListener() {
						 	public void actionPerformed(ActionEvent e) {
						 		int flag=1;
						 		if (!comboBox_book_subject.getSelectedItem().toString().isEmpty())
						 		{
						 			
										for(int i=0;i< str_subjects.size();i++)
										{
											if(str_subjects.get(i).equals(comboBox_book_subject.getSelectedItem()))
											{	
												flag=0;
										   		break;
										   	}
										}
										if(flag==1)
						 			str_subjects.add(comboBox_book_subject.getSelectedItem().toString());
							 		
						 		}
						 		
						 	}
						 });
					 
		btnAdd_author_name.setBounds(262, 147, 66, 28);
		panel.add(btnAdd_author_name);
		
		
		 
	
		comboBox_book_subject.setBounds(127, 195, 115, 23);
		panel.add(comboBox_book_subject);
		
		JLabel lblBookAdition = new JLabel("book adition:");
		lblBookAdition.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblBookAdition.setBounds(15, 63, 88, 14);
		panel.add(lblBookAdition);
		
		textField_book_adition = new JTextField();
		textField_book_adition.setBounds(127, 62, 115, 20);
		panel.add(textField_book_adition);
		textField_book_adition.setColumns(10);
		
		JLabel lblDescription = new JLabel("description:");
		lblDescription.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblDescription.setBounds(10, 386, 83, 18);
		panel.add(lblDescription);
		
		
		textArea_description.setBounds(103, 391, 205, 58);
		panel.add(textArea_description);
		
		JLabel lblLocation = new JLabel("location:");
		lblLocation.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblLocation.setBounds(15, 106, 71, 14);
		panel.add(lblLocation);
		
		textField_location = new JTextField();
		textField_location.setBounds(127, 105, 115, 20);
		panel.add(textField_location);
		textField_location.setColumns(10);
		
		JLabel lblTableOfContext = new JLabel("table of context:");
		lblTableOfContext.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblTableOfContext.setBounds(10, 310, 107, 14);
		panel.add(lblTableOfContext);
		
		JLabel lblToAddEach = new JLabel("to add each author or subject press add");
		lblToAddEach.setFont(new Font("Segoe Print", Font.BOLD, 11));
		lblToAddEach.setForeground(Color.RED);
		lblToAddEach.setBounds(336, 174, 238, 14);
		panel.add(lblToAddEach);
		
		
		//=====================================
		//final JFileChooser fc = new JFileChooser();
		
		
		btnNewButton = new JButton("Choose Description File (PDF)");
		btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				JFileChooser chooser = new JFileChooser();  
				chooser.setFileFilter(new FileFilter() {
			          
					public boolean accept(File f) {
			            return f.getName().toLowerCase().endsWith(".pdf")
			                || f.isDirectory();
			          }

			          public String getDescription() {
			            return "PDF Files";
			          }
			        });
			        
			    //chooser.setFileSelectionMode(JFileChooser.APPROVE_OPTION);
			    int option = chooser.showOpenDialog(Add_New_Item_Panel.this);
			    if (option == JFileChooser.APPROVE_OPTION) {
			    	if (chooser.getSelectedFile()!=null)
			    	{
			    		JOptionPane.showMessageDialog(null,chooser.getSelectedFile().getName());
			    	}
			    	else
			    		JOptionPane.showMessageDialog(null,"nothing");
			    }
			    else {
			    	JOptionPane.showMessageDialog(null,"You canceled.");
			     }
			    //getting the pdf file
			    // Open file
		       
			    String name = null;
			    Charset encoding = Charset.defaultCharset();
			    name = chooser.getSelectedFile().getAbsolutePath();
			    
			    RandomAccessFile f;
				try {
					f = new RandomAccessFile(new File(name), "r");
					// Get and check length
		            long longlength = f.length();
		            int length = (int) longlength;
		            if (length != longlength) throw new IOException("File size >= 2 GB");

		            // Read file and return data
		            byte[] data = new byte[length];
		            f.readFully(data);
		            f.close();
		         
		            decoded = new String(data, "ISO-8859-1");//String to send to server
		            System.out.println("decoded:" + decoded);

//		            byte[] encoded = decoded.getBytes("ISO-8859-1"); //String to getting to server
//		           // System.out.println("encoded:" + java.util.Arrays.toString(encoded));
//		            
//		            FileOutputStream fos = new FileOutputStream("temp\\Description.pdf");
//		            fos.write(encoded);
//		            fos.close();
		            
		            
		            
				} 
				catch (Exception e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace()
					;
				}

		        
			    
			     
			}
		});
		btnNewButton.setBounds(127, 310, 238, 28);
		panel.add(btnNewButton);

	}

	/**
	 * @return  book name that the user enter
	 */
	public String get_book_name()
	{
		return textbook_name.getText();
	}
	/**
	 * 
	 * @return location that the user enter
	 */
	public String get_location()
	{
		return textField_location.getText();
	}
	/**
	 * 
	 * @return addition that the user enter
	 */
	public String get_book_adition()
	{
		return textField_book_adition.getText();
	}
	/**
	 * 
	 * @return"1"-if in the comboBox_wanted the user choose "yes"
	 *		  "2"-if in the comboBox_wanted the user choose "no"
	 */
	public String get_wanted()
	{
		if (comboBox_wanted.getSelectedItem().toString().equalsIgnoreCase("yes"))
			return "1";
		
			return "0";
			
				
	}
	/**
	 * 
	 * @return description that the user enter
	 */
	public String get_description()
	{
		return textArea_description.getText();
	}
/**
 * 
 * @return all the authors id that the user choose
 */
	public String[] get_autor_name()
	{
			String[] str=new String[str_autor_name.size()];
			for (int i=0;i<str_autor_name.size();i++)
				for (int j=0;j<all_authors_name.length;j++)
				{ if(!all_authors_id[j].equals(""))
					if(str_autor_name.get(i).equals(all_authors_name[j]))
					str[i]=all_authors_id[j];
				}
			return str;
	}
	/**
	 * @return all the subjects id that the user choose
	 */
	public String[] get_subjects()
	{
		
		String[] str=new String[str_subjects.size()];
		for (int i=0;i<str_subjects.size();i++)
			for (int j=0;j<all_subject_name.length;j++)
			{ if(!all_subject_name[j].equals(""))
				if(str_subjects.get(i).equals(all_subject_name[j]))
				str[i]=all_subject_id[j];
			}
		return str;
	}

	/**
	 * this method display showMessageDialog with a success msg
	 */
	public void next_screen_success()
	{
		JOptionPane.showMessageDialog(this,"apply success");
	}
	/**
	 * this method display showMessageDialog with a faild msg
	 * @param msg
	 */
	public void next_screen_faild(String msg)
	{
		JOptionPane.showMessageDialog(this,"apply faild "+msg);
	}
	/**
	 * this method empty all the text field
	 */
	public void empty_text_fields()
	{
		textbook_name.setText(null);
		textField_book_adition.setText(null);
		textField_location.setText(null);
		textArea_description.setText(null);
		on_screen_load();
	}
	
	@Override
	public void next_screen() {
		// TODO Auto-generated method stub
		
		
	}

	@Override
	public void prev_screen() {
		// TODO Auto-generated method stub
		
	}

	@Override
	/**
	 * this method is the first method we call in this screen
	 * the main purpose of this method is to initialize the comboBox's 
	 * that this panel use, here we call the controller of this panel
	 * to get all author and subjects names and id's and set them at the combobox
	 */
	public void on_screen_load() {
		
		String[] line;
		 str_autor_name=new ArrayList<String>();
		 str_subjects=new ArrayList<String>();
		add_new_item_controler=new Add_new_item_controler();//create referents to the controller
		all_authors=add_new_item_controler.get_all_authors();//call the controller method get_all_authors() that return array list with all the authors
		all_subject=add_new_item_controler.get_all_subjects();//call the controller method get_all_subjects() that return array list with all the subjects
		/*
		 * make String[] with names and id's of authors
		 */
		
		all_authors_name = new String[all_authors.size()+1];
		all_authors_id = new String[all_authors.size()+1];
		all_authors_name[0] = "";
		all_authors_id[0] =  "";
		for (int i = 1 ; i <= all_authors.size() ; i++)
		{
			line = all_authors.get(i-1).split(",");
			all_authors_id[i] = line[0];
			all_authors_name[i] = line[1];
			
		}
		//set String[] all_authors_name to the commboBox with all the authors names
		comboBox_author_name.setModel(new DefaultComboBoxModel(all_authors_name));
		/*
		 * make String[] with names and id's of subjects
		 */
		
		all_subject_name = new String[all_subject.size()+1];
		all_subject_id = new String[all_subject.size()+1];
		all_subject_name[0] = "";
		all_subject_id[0] =  "";
		for (int i = 1 ; i <= all_subject.size() ; i++)
		{
			line = all_subject.get(i-1).split(",");
			all_subject_id[i] = line[0];
			all_subject_name[i] = line[1];
			
		}
		//set String[] all_subject_name to the commboBox with all the subjects names
		comboBox_book_subject.setModel(new DefaultComboBoxModel(all_subject_name));
		
	}

	@Override
	public void on_screen_unload() {
		// TODO Auto-generated method stub
		
	}
}
